---
import type { CollectionEntry } from 'astro:content';
import PillListFlat from '@components/Lists/PillListFlat';
import OwnersList from '@components/Lists/OwnersList';
import type { CollectionMessageTypes } from '@types';
import * as path from 'path';
import VersionList from '@components/Lists/VersionList.astro';
import { buildUrl } from '@utils/url-builder';
import { FileDownIcon, ScrollText, Workflow, RssIcon } from 'lucide-react';
import RepositoryList from '@components/Lists/RepositoryList.astro';
import { getOwner } from '@utils/collections/owners';
import CustomSideBarSectionList from '@components/Lists/CustomSideBarSectionList.astro';
import config from '@config';
import { getSchemaFormatFromURL } from '@utils/collections/schemas';
import { isChangelogEnabled, isVisualiserEnabled } from '@utils/feature';
interface Props {
  message: CollectionEntry<CollectionMessageTypes>;
}

const { message } = Astro.props;

const producers = (message.data.producers as CollectionEntry<'services'>[]) || [];
const consumers = (message.data.consumers as CollectionEntry<'services'>[]) || [];
const channels = (message.data.messageChannels as CollectionEntry<'channels'>[]) || [];

const ownersRaw = message.data?.owners || [];
const owners = await Promise.all<ReturnType<typeof getOwner>>(ownersRaw.map(getOwner));
const filteredOwners = owners.filter((o) => o !== undefined);

const resourceGroups = message.data?.resourceGroups || [];

const attachments = message.data.attachments || [];

const attachmentsList = attachments.map((a) => {
  const attachmentIsURL = typeof a === 'string';
  return {
    label: attachmentIsURL ? a : (a.title ?? a.url),
    href: attachmentIsURL ? a : a.url,
    icon: attachmentIsURL ? 'ExternalLinkIcon' : (a.icon ?? 'ExternalLinkIcon'),
    target: '_blank' as const,
    subgroup: attachmentIsURL ? undefined : (a.type ?? ''),
  };
});

const producerList = producers.map((p) => ({
  label: `${p.data.name}`,
  tag: `v${p.data.version}`,
  collection: p.collection,
  href: buildUrl(`/docs/services/${p.data.id}/${p.data.version}`),
}));

const consumerList = consumers.map((p) => ({
  label: `${p.data.name}`,
  tag: `v${p.data.version}`,
  collection: p.collection,
  href: buildUrl(`/docs/services/${p.data.id}/${p.data.version}`),
}));

const ownersList = filteredOwners.map((o) => ({
  label: o.data.name,
  type: o.collection,
  badge: o.collection === 'users' ? o.data.role : 'Team',
  avatarUrl: o.collection === 'users' ? o.data.avatarUrl : '',
  href: buildUrl(`/docs/${o.collection}/${o.data.id}`),
}));

const channelList = channels.map((c) => ({
  label: `${c.data.name}`,
  tag: `v${c.data.version}`,
  collection: c.collection,
  href: buildUrl(`/docs/channels/${c.data.id}/${c.data.version}`),
}));

const getType = (type: string) => {
  switch (type) {
    case 'queries':
      return 'Query';
    default:
      return message.collection.slice(0, -1);
  }
};

const getProducerEmptyMessage = (type: string) => {
  const value = type.toLowerCase();
  switch (value) {
    case 'query':
    case 'command':
      return `This ${value} does not get invoked by any services.`;
    default:
      return `This ${value} does not get produced by any services.`;
  }
};

const getConsumerEmptyMessage = (type: string) => {
  const value = type.toLowerCase();
  switch (value) {
    case 'query':
    case 'command':
      return `This ${value} does not invoke any service.`;
    default:
      return `This ${value} does not get consumed by any services.`;
  }
};

const type = getType(message.collection);

const isRSSEnabled = config.rss?.enabled;

// @ts-ignore
const publicPath = message?.catalog?.publicPath;

const schemaFilePath = message?.data?.schemaPath;
const schemaURL = path.join(publicPath, schemaFilePath || '');

const shouldRenderSideBarSection = (section: string) => {
  if (!message.data.detailsPanel) {
    return true;
  }
  // @ts-ignore
  return message.data.detailsPanel[section]?.visible ?? true;
};
---

<aside class="sticky top-28 left-0 space-y-8 h-full overflow-y-auto py-4">
  <div class="">
    {
      resourceGroups
        .filter((section) => section.items.length > 0 && section.sidebar)
        .map((section) => <CustomSideBarSectionList section={section} />)
    }
    {
      producerList.length > 0 && shouldRenderSideBarSection('producers') && (
        <PillListFlat
          color="pink"
          title={`Producers (${producerList.length})`}
          pills={producerList}
          emptyMessage={getProducerEmptyMessage(type)}
          client:load
        />
      )
    }
    {
      consumerList.length > 0 && shouldRenderSideBarSection('consumers') && (
        <PillListFlat
          color="pink"
          title={`Consumers (${consumerList.length})`}
          pills={consumerList}
          emptyMessage={getConsumerEmptyMessage(type)}
          client:load
        />
      )
    }
    {
      channelList.length > 0 && shouldRenderSideBarSection('channels') && (
        <PillListFlat color="pink" title={`Channels (${channelList.length})`} pills={channelList} client:load />
      )
    }

    {
      message.data.versions && shouldRenderSideBarSection('versions') && (
        <VersionList
          title={`Versions (${message.data.versions?.length})`}
          versions={message.data.versions}
          collectionItem={message}
        />
      )
    }

    {
      message.data.attachments && shouldRenderSideBarSection('attachments') && (
        <PillListFlat
          title={`Attachments (${attachmentsList.length})`}
          pills={attachmentsList}
          emptyMessage={`This ${type} does not have any attachments.`}
          color="pink"
          client:load
        />
      )
    }

    {
      ownersList.length > 0 && shouldRenderSideBarSection('owners') && (
        <OwnersList
          title={`Owners (${ownersList.length})`}
          owners={ownersList}
          emptyMessage={`This ${type} does not have any documented owners.`}
          client:load
        />
      )
    }

    {
      message.data.repository && shouldRenderSideBarSection('repository') && (
        <RepositoryList repository={message.data.repository?.url} language={message.data.repository?.language} />
      )
    }

    {
      isRSSEnabled && (
        <div class="mx-auto pb-8 w-full max-w-lg divide-y divide-white/5 rounded-xl bg-white/5">
          <span class="text-sm text-black font-semibold group-data-[hover]:text-black/80 capitalize">{type} RSS Feed</span>
          <ul role="list" class="space-y-2 mt-2">
            <li class="has-tooltip rounded-md text-gray-600 group px-1 w-full hover:bg-gradient-to-l hover:from-purple-500 hover:to-purple-700 hover:text-white hover:font-normal  ">
              <a class={`flex items-center space-x-2`} target="_blank" href={buildUrl(`/rss/${message.collection}/rss.xml`)}>
                <RssIcon className="h-4 w-4 text-gray-800 group-hover:text-white" strokeWidth={1} />
                <span class="font-light text-sm truncate">RSS Feed</span>
              </a>
            </li>
          </ul>
        </div>
      )
    }

    <div class="space-y-2">
      {
        message?.data?.schemaPath && (
          <a
            href={buildUrl(schemaURL, true)}
            download={`${message.data.name}(${message.data.version})-${schemaFilePath}`}
            class="flex items-center justify-center space-x-2 text-center rounded-md w-full bg-white px-3.5 py-2.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-100/60 hover:text-primary"
          >
            <FileDownIcon strokeWidth={2} size={16} />
            <span>Download {getSchemaFormatFromURL(schemaURL)?.toUpperCase()} schema</span>
          </a>
        )
      }
      {
        isVisualiserEnabled() && (
          <a
            href={buildUrl(`/visualiser/${message.collection}/${message.data.id}/${message.data.version}`)}
            class="flex items-center justify-center space-x-2 text-center rounded-md w-full bg-white px-3.5 py-2.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-100/60 hover:text-primary"
          >
            <Workflow strokeWidth={2} size={16} />
            <span class="block">View in visualiser</span>
          </a>
        )
      }
      {
        isChangelogEnabled() && shouldRenderSideBarSection('changelog') && (
          <a
            href={buildUrl(`/docs/${message.collection}/${message.data.id}/${message.data.latestVersion}/changelog`)}
            class="flex items-center space-x-2 justify-center text-center rounded-md w-full bg-white px-3.5 py-2.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-100/60 hover:text-primary"
          >
            <ScrollText strokeWidth={2} size={16} />
            <span class="block">Read changelog</span>
          </a>
        )
      }
    </div>
  </div>
</aside>
